package com.xinxin.blockchain.common.service;

import com.xinxin.base.service.IRedisService;
import com.xinxin.base.util.legacy.TimeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ys
 * @date 2021/5/20
 */
@Service
public class RedisService implements IRedisService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, Object> valOpsObj;
    @Resource(name = "redisTemplate")
    private HashOperations<String, String, Object> hashOpsObj;
    @Resource(name = "redisTemplate")
    private SetOperations<String, Object> setOpsObj;
    @Resource(name = "redisTemplate")
    private ZSetOperations<String, Object> zSetOpsObj;
    @Resource(name = "redisTemplate")
    private ListOperations<String, Object> listOpsObj;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valOpsStr;

    @Override
    public void setString(String key, String value) {
        valOpsStr.set(key, value);
    }

    @Override
    public void setString(String key, String value, long timeout, TimeUnit unit) {
        valOpsStr.set(key, value, timeout, unit);
    }

    @Override
    public void setObject(String key, Object value) {
        valOpsObj.set(key, value);
    }

    @Override
    public void setObject(String key, Object value, long timeout, TimeUnit unit) {
        valOpsObj.set(key, value, timeout, unit);
    }

    @Override
    public String getString(String key) {
        return valOpsStr.get(key);
    }

    @Override
    public <T> T getObject(String key, Class<T> clazz) {
        return clazz.cast(valOpsObj.get(key));
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    @Override
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    @SuppressWarnings("all")
    public Boolean setnx(String key, Object value, long timeout, TimeUnit unit) {
        return redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            RedisSerializer keySerializer = redisTemplate.getKeySerializer();
            RedisSerializer valueSerializer = redisTemplate.getValueSerializer();

            Boolean result = connection.set(keySerializer.serialize(key), valueSerializer.serialize(value),
                    Expiration.from(timeout, unit), RedisStringCommands.SetOption.ifAbsent());

            /*
            Object obj = connection.execute("set", keySerializer.serialize(key), valueSerializer.serialize(value),
                    "NX".getBytes(StandardCharsets.UTF_8),
                    "EX".getBytes(StandardCharsets.UTF_8),
                    String.valueOf(timeout).getBytes(StandardCharsets.UTF_8));
            */

            return result;
        });
    }

    private static final int RIGHT_LENGTH = 9;

    @Override
    public double arithmetic2RedisScore(int score, LocalDateTime endTime) {
        Duration duration = Duration.between(LocalDateTime.now(), endTime);
        long remainSeconds = duration.getSeconds();
        if (remainSeconds > 999_999_999L) {
            throw new RuntimeException("分数转换错误，时间超长: " + TimeUtils.format(endTime));
        }

        return score * Math.pow(10, RIGHT_LENGTH) + remainSeconds;
    }

    @Override
    public int redis2ArithmeticScore(Double score) {
        Double result = score / Math.pow(10, RIGHT_LENGTH);
        return result.intValue();
    }

    @Override
    public void arithmeticAdd(String key, Object value, int score, LocalDateTime endTime) {
        add(key, value, arithmetic2RedisScore(score, endTime));
    }

    @Override
    public int arithmeticScore(String key, Object value) {
        return redis2ArithmeticScore(score(key, value));
    }

    @Override
    public void add(String key, Object value, double score) {
        zSetOpsObj.add(key, value, score);
    }

    @Override
    public Double score(String key, Object value) {
        Double score = zSetOpsObj.score(key, value);
        return score == null ? -1 : score;
    }

    @Override
    public Long rank(String key, Object value) {
        Long rank = zSetOpsObj.reverseRank(key, value);
        return rank == null ? -1 : rank;
    }

    @Override
    public Set<ZSetOperations.TypedTuple<Object>> rangeWithScores(String key, long start, long end) {
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = zSetOpsObj.reverseRangeWithScores(key, start, end);
        return CollectionUtils.isEmpty(typedTuples) ? Collections.emptySet() : typedTuples;
    }

    @Override
    public Set<Object> range(String key, long start, long end) {
        Set<Object> range = zSetOpsObj.reverseRange(key, start, end);
        return CollectionUtils.isEmpty(range) ? Collections.emptySet() : range;
    }
}
